﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Core.DataAccess.Interfaces;
using Core.DataAccess.Tools.Interfaces;

namespace Core.DataAccess.Implementations
{
    //Common class for all DataProviders
    public class ModelDataProvider<T>:DataProviderBase<T>,IModelDataProvider<T> 
        
    {
        #region Implementation of IModelDataProvider<T>

        
        public ModelDataProvider(IConversation conversation, IRepository<T> repository) 
            : base(conversation, repository)
        {
            
        }

        public virtual IList<T> GetAll()
        {
            try
            {
                return Repository.GetAll().List<T>();
            }
            catch(NHibernate.Exceptions.GenericADOException e)
            {
                throw new Exceptions.CorruptedDatabaseException(e.Message, e);
            }
        }

        public virtual T Save(T entity)
        {
            //if (Get(entity.Id) != null)
               // throw new Exceptions.DuplicationEntityException();
                Repository.Save(entity);
                return entity;
        }

        public virtual T Get<U>(U id)
        {
            try
            {
                return Repository.Get(id);
            }
            catch (NHibernate.Exceptions.GenericADOException e)
            {
                throw new Exceptions.CorruptedDatabaseException(e.Message, e);
            }
        }

        public virtual T Update(T entity)
        {
            try
            {
               Repository.Update(entity);
            }
            catch (NHibernate.Exceptions.GenericADOException e)
            {
                throw new Exceptions.CorruptedDatabaseException(e.Message, e);
            }
            return entity;
        }

        public virtual void Delete<U>(U id)
        {
            try
            {
                Repository.Delete(id);
            }
            catch (NHibernate.Exceptions.GenericADOException e)
            {
                throw new Exceptions.CorruptedDatabaseException(e.Message, e);
            }
        }

        #endregion
    }
}
